#include <inttypes.h>
#include "config.h"
#include "irq.h"
#include "fio.h"
#include "kbd.h"

#define KBD_CLK_MASK (1 << 23)	// P2.23
#define KBD_CLK_FIO FIO2PIN
#define KBD_CLK_PORT 2

#define KBD_DAT_MASK (1 << 23)	// P3.23
#define KBD_DAT_FIO FIO3PIN
#define KBD_DAT_PORT 3

static uint8_t scan_table[] = {
/*         00    01    02    03    04    05    06    07    08    09    0A    0B    0C    0D    0E    0F */
/* 00 */ 0x00, 0x43, 0x00, 0x3f, 0x3d, 0x3b, 0x3c, 0x58, 0x00, 0x44, 0x42, 0x40, 0x3e, 0x0f, 0x29, 0x00,
/* 10 */ 0x00, 0x46, 0x60, 0x00, 0x61, 0x10, 0x02, 0x00, 0x00, 0x00, 0x2c, 0x1f, 0x1e, 0x11, 0x03, 0x00,
/* 20 */ 0x00, 0x2e, 0x2d, 0x20, 0x12, 0x05, 0x04, 0x00, 0x00, 0x39, 0x2f, 0x21, 0x14, 0x13, 0x06, 0x00,
/* 30 */ 0x00, 0x31, 0x30, 0x23, 0x22, 0x15, 0x07, 0x00, 0x00, 0x00, 0x32, 0x24, 0x16, 0x08, 0x09, 0x00,
/* 40 */ 0x00, 0x33, 0x25, 0x17, 0x18, 0x0b, 0x0a, 0x00, 0x00, 0x34, 0x35, 0x26, 0x27, 0x19, 0x0c, 0x00,
/* 50 */ 0x00, 0x00, 0x28, 0x00, 0x1a, 0x0d, 0x00, 0x00, 0x3a, 0x60, 0x1c, 0x1b, 0x00, 0x2b, 0x00, 0x00,
/* 60 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x4f, 0x00, 0x4b, 0x47, 0x74, 0x00, 0x00,
/* 70 */ 0x52, 0x62, 0x50, 0x69, 0x4d, 0x48, 0x01, 0x65, 0x57, 0x68, 0x64, 0x67, 0x66, 0x63, 0x6a, 0x00,
/* 80 */ 0x00, 0x00, 0x00, 0x41, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};

void vGpio2Handler (void) __attribute__ ((interrupt("IRQ")));

int keyboard_init(void)
{
    FIOInit(KBD_CLK_PORT, DIR_IN, KBD_CLK_MASK);
    FIOInit(KBD_DAT_PORT, DIR_IN, KBD_DAT_MASK);

    if (Install_IRQ(EINT3_INT, (void *)vGpio2Handler, LOWEST_PRIORITY) == FALSE)
	return FALSE;

    IO2_INT_EN_F |= KBD_CLK_MASK;

    return TRUE;
}
void vGpio2Handler(void)
{
    static uint8_t bkey = 0, bcount = 0, keyup = 0, e1prefix = 0, skipkeys = 0, scancode = 0;

    if ((IO_INT_STAT & (1 << 2)) &&
	(IO2_INT_STAT_F & KBD_CLK_MASK)) {
	if (bcount < 10) {
	    if (bcount > 0 && bcount < 9)
		bkey = (bkey >> 1) | ((KBD_DAT_FIO & KBD_DAT_MASK)?0x80:0);
	    bcount++;
	} else {
	    if (skipkeys) {
		skipkeys--;
		bkey = 0;
	    }
	    if (bkey == 0xf0)
		keyup = 0x80;
	    else if (bkey == 0xe1)
		e1prefix = 1;
	    else {
		if (bkey && bkey < 0x90) {
		    if (e1prefix) {
			if (bkey == 0x14)
			    scancode = 0x6f;
			skipkeys = 6;
			e1prefix = 0;
		    } else
			scancode = scan_table[bkey] | keyup;
		    if (scancode)
			keyboard_handler(scancode);
		}
		keyup = 0;
	    }
	    bcount = 0;
	    bkey= 0;
	}
	IO2_INT_CLR = KBD_CLK_MASK;
    }
    VICVectAddr = 0;
}
